package com.learn.spring.handler;

import com.learn.spring.entity.FluxUser;
import com.learn.spring.service.FluxService;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import static org.springframework.web.reactive.function.BodyInserters.fromValue;


public class FluxHandler {

    private FluxService fluxService;

    public FluxHandler(FluxService fluxService) {
        this.fluxService = fluxService;
    }

    // 根据ID查
    public Mono<ServerResponse> findUserById(ServerRequest request) {
        int id = Integer.parseInt(request.pathVariable("id"));
        Mono<FluxUser> userMono = this.fluxService.getUserById(id);
        return userMono.flatMap(
                user -> ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(fromValue(user))
        ).switchIfEmpty(ServerResponse.notFound().build());
    }

    // 查所有
    public Mono<ServerResponse> allUser(ServerRequest request) {
        Flux<FluxUser> allUser = this.fluxService.getAllUser();
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(allUser, FluxUser.class);
    }

    // 添加
    public Mono<ServerResponse> addUser(ServerRequest request) {
        Mono<FluxUser> fluxUserMono = request.bodyToMono(FluxUser.class);
        return ServerResponse.ok().build(this.fluxService.addUser(fluxUserMono));
    }
}
